package com.zrrd.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.zrrd.model.article.pojos.ApArticleContent;
import com.zrrd.model.common.dtos.ResponseResult;
import com.zrrd.model.common.enums.AppHttpCodeEnum;
import com.zrrd.model.search.dtos.UserSearchDto;
import com.zrrd.search.service.ArticleSearchService;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author WanJl
 * @version 1.0
 * @title ArticleSearchServiceImpl
 * @description
 * @create 2023/10/6 14:12
 */
@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient client;
    /**
     * ES新闻分页搜索
     *
     * @param dto
     * @return
     * @throws IOException
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1、检查参数
        if (dto==null|| StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2、设置查询条件
        SearchRequest searchRequest=new SearchRequest("app_info_article");
        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
        //3、布尔查询
        BoolQueryBuilder boolQueryBuilder=QueryBuilders.boolQuery();
        //4、对关键字分词，分词之后查询
        QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords())
                .field("title")
                .field("content")
                .defaultOperator(Operator.OR);
        boolQueryBuilder.must(queryStringQueryBuilder);
        //查询小于mindate的数据
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders
                .rangeQuery("publishTime")
                .lt(dto.getMinBehotTime()
                        .getTime());
        boolQueryBuilder.filter(rangeQueryBuilder);
        //5、分页查询
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(dto.getPageSize());
        //按照发布时间倒序排序查询
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);
        //6、设置结果高亮
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color:red;font-size:inherit'>");
        highlightBuilder.postTags("</font>");
        searchSourceBuilder.highlighter(highlightBuilder);
        //7、发起请求
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        //获取响应结果
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);


        //8、把结果封装并返回
        //解析响应
        SearchHit[] hits = searchResponse.getHits().getHits();
        List<Map> list=new ArrayList<>();
        //遍历文档数组
        for (SearchHit hit : hits) {
            //获取文档JSON
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);
            //处理高亮
            if (hit.getHighlightFields()!=null&&hit.getHighlightFields().size()>0){
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                String title = StringUtils.join(titles);
                //高亮标题
                map.put("h_title",title);
            }else {
                //显示原始标题
                map.put("h_title",map.get("title"));
            }
            list.add(map);
        }
        return ResponseResult.okResult(list);
    }
}
